package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.School;
import com.example.mapper.SchoolMapper;
import com.example.service.SchoolService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class SchoolServiceImpl extends ServiceImpl<SchoolMapper, School> implements SchoolService {
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addCanteen(Long schoolId, String canteenUuid) {
        School school = getById(schoolId);
        if (school == null) {
            return false;
        }
        try {
            List<String> uuids = school.getCanteenUuids() != null ? 
                objectMapper.readValue(school.getCanteenUuids(), new TypeReference<List<String>>() {}) : 
                new ArrayList<>();
            if (!uuids.contains(canteenUuid)) {
                uuids.add(canteenUuid);
                school.setCanteenUuids(objectMapper.writeValueAsString(uuids));
                return updateById(school);
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException("添加食堂UUID失败", e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCanteen(Long schoolId, String canteenUuid) {
        School school = getById(schoolId);
        if (school == null) {
            return false;
        }
        try {
            List<String> uuids = school.getCanteenUuids() != null ? 
                objectMapper.readValue(school.getCanteenUuids(), new TypeReference<List<String>>() {}) : 
                new ArrayList<>();
            if (uuids.remove(canteenUuid)) {
                school.setCanteenUuids(objectMapper.writeValueAsString(uuids));
                return updateById(school);
            }
            return true;
        } catch (Exception e) {
            throw new RuntimeException("移除食堂UUID失败", e);
        }
    }

    @Override
    public School getByCanteenUuid(String canteenUuid) {
        LambdaQueryWrapper<School> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(School::getCanteenUuids, canteenUuid);
        return getOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSchool(School school) {
        // 如果school的id为null，说明是新增
        if (school.getId() == null) {
            return save(school);
        }
        // 否则是更新
        return updateById(school);
    }
} 